package com.wsx.boots.auth.config;

import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangshuaixin on 17/4/23.
 */
public class StatelessAccessControlFilter extends AccessControlFilter {

    /**
     * first 是否允许访问
     * @param request
     * @param response
     * @param o 拦截的参数部分
     * @return 如果允许访问返回true，直接提交给下一个filter
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {

        return false;
    }

    /**
     * second 如果返回true就是需要继续处理
     * @param request
     * @param response
     * @return 返回true标示正常业务逻辑，返回false表示拦截已经处理，直接返回客户端
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String clientDigest = request.getParameter("digest");
        String name = request.getParameter("name");

        Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());
        params.remove("digest");

        StatelessAuthenticationToken token = new StatelessAuthenticationToken(name, params, clientDigest);
        try {
            getSubject(request,response).login(token);
        } catch (Exception e) {
            e.printStackTrace();
            onLoginFail(response);
            return false;
        }
        return true;
    }

    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("error");
    }
}
